package in.iqing.view.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.makeramen.roundedimageview.RoundedTransformationBuilder;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Transformation;

import java.text.SimpleDateFormat;

import butterknife.Bind;
import butterknife.OnClick;
import in.iqing.app.R;
import in.iqing.base.BaseActivity;
import in.iqing.control.helper.ImageResourceHelper;
import in.iqing.control.helper.IntentHelper;
import in.iqing.control.util.IntentUtil;
import in.iqing.model.bean.Book;
import in.iqing.model.db.DBHelper;

/**
 * Created by ZuoShu on 15/7/8.
 */
public class BookActivity extends BaseActivity {
    private Book book;

    @Bind(R.id.title_text)
    TextView id;

    @Bind(R.id.cover_image)
    ImageView coverImage;

    @Bind(R.id.book_title_text)
    TextView bookTitle;

    @Bind(R.id.views_text)
    TextView views;

    @Bind(R.id.press_text)
    TextView press;

    @Bind(R.id.author_text)
    TextView author;

    @Bind(R.id.update_text)
    TextView updateTime;

    @Bind(R.id.intro_text)
    TextView introduce;

    @Bind(R.id.directory_text)
    TextView directory;

    @Bind(R.id.last_update_text)
    TextView lastUpdate;

    @Bind(R.id.relative_text)
    TextView relativeBook;

    @Bind(R.id.intro_abbr_arrow)
    ImageView introduceAbbrIndicator;

    @Bind(R.id.subscribe_image)
    ImageView subscribeImage;

    @Bind(R.id.subscribe_text)
    TextView subscribeText;

    @Bind(R.id.continue_read_text)
    TextView continueRead;

    @Bind(R.id.begin_read_text)
    TextView beginRead;

    private boolean showAbbrIntroduce;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book);
    }

    @Override
    protected void onInitialize(Bundle savedInstanceState) {
        super.onInitialize(savedInstanceState);
        book = (Book) getIntent().getSerializableExtra("book");
        setBook();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setSubscribe();
        setContinueRead();
    }

    private void setBook() {
        id.setText(String.valueOf(book.getId()));
        Transformation coverTransformation = new RoundedTransformationBuilder()
                .cornerRadius(getResources().getDimension(R.dimen.round_image_radius))
                .borderWidth(getResources().getDimension(R.dimen.image_border_width))
                .borderColor(getResources().getColor(R.color.iqing_yellow))
                .oval(false)
                .build();
        RequestCreator createor = TextUtils.isEmpty(book.getCover())
                ? Picasso.with(this).load(R.drawable.image_loading_1x1)
                : Picasso.with(this).load(ImageResourceHelper.generateCoverImageUrl(book.getCover()));
        createor.placeholder(R.drawable.image_loading_1x1)
                .error(R.drawable.image_error)
                .transform(coverTransformation)
                .resizeDimen(R.dimen.book_cover_width, R.dimen.book_cover_height)
                .centerCrop()
                .into(coverImage);
        bookTitle.setText(book.getTitle());
        views.setText(String.valueOf(book.getViews()));
        press.setText(book.getPress());
        author.setText(book.getAuthor());
        updateTime.setText(generateUpdateTime());
        introduce.setText(getString(R.string.label_intro, book.getIntro()));
        introduce.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (introduce.getLineCount() > 3) {
                    introduce.setMaxLines(3);
                    introduceAbbrIndicator.setVisibility(View.VISIBLE);
                    showAbbrIntroduce = true;
                } else {
                    showAbbrIntroduce = false;
                }
                introduce.removeOnLayoutChangeListener(this);
            }
        });

        directory.setText(
                getString(R.string.activity_qing_book_directory_content
                        , String.valueOf(book.getVolumeCount())
                        , String.valueOf(book.getChapterCount()))
        );
        lastUpdate.setText(
                getString(R.string.activity_qing_book_last_update_content
                        , book.getLastVolumeTitle()
                        , book.getLastChapterTitle())
        );
        // TODO load relative books
        relativeBook.setText(
                getString(R.string.activity_qing_book_relative_content, String.valueOf(0))
        );
    }

    private void setContinueRead() {
        if (DBHelper.getInstance().getBookmark(book.getId()) == null) {
            beginRead.setVisibility(View.VISIBLE);
            continueRead.setVisibility(View.GONE);
        } else {
            beginRead.setVisibility(View.GONE);
            continueRead.setVisibility(View.VISIBLE);
        }
    }

    private void setSubscribe() {
        if (DBHelper.getInstance().hasSubscribe(book)) {
            subscribeImage.setImageResource(R.drawable.icon_subscribe_disable);
            subscribeText.setText(R.string.activity_qing_book_has_subscribed);
            subscribeText.setTextColor(getResources().getColor(R.color.primary_text));
        } else {
            subscribeImage.setImageResource(R.drawable.icon_subscribe_enable);
            subscribeText.setText(R.string.activity_qing_book_subscribe);
            subscribeText.setTextColor(getResources().getColor(R.color.iqing_blue));
        }
    }

    private String generateUpdateTime() {
        SimpleDateFormat df = new SimpleDateFormat(getString(R.string.activity_qing_book_update_time_format));
        return df.format(book.getUpdatedTime());
    }

    @OnClick(R.id.subscribe_layout)
    public void onSubscribeClick(View v) {
        if (DBHelper.getInstance().hasSubscribe(book)) {
            DBHelper.getInstance().deleteSubscribe(book);
        } else {
            DBHelper.getInstance().addSubscribe(book);
        }
        setSubscribe();
    }

    @OnClick(R.id.begin_read_text)
    public void onBeginReadClick(View v) {
        DBHelper.getInstance().saveBook(book);
        Bundle extra = getIntent().getExtras();
        extra.putSerializable("book", book);
        extra.putBoolean("from_book_start", true);
        IntentUtil.startActivity(getActivity(), ContentActivity.class, extra);
    }

    @OnClick(R.id.continue_read_text)
    public void onContinueReadClick(View v) {
        DBHelper.getInstance().saveBook(book);
        Bundle extra = getIntent().getExtras();
        extra.putSerializable("book", book);
        extra.putBoolean("from_bookmark", true);
        IntentUtil.startActivity(getActivity(), ContentActivity.class, extra);
    }

    @OnClick(R.id.relative_books_layout)
    public void onShowRelativeClick(View v) {
//        ToastUtil.show(this, "TODO:相关作品");
    }

    @OnClick(R.id.directory_layout)
    public void onDirectoryClick(View v) {
        DBHelper.getInstance().saveBook(book);
        Bundle data = new Bundle();
        data.putSerializable("book", book);
        IntentHelper.startActivity(this, DirectoryActivity.class, data);
    }

    @OnClick(R.id.last_update_layout)
    public void onLastUpdateClick(View v) {
        DBHelper.getInstance().saveBook(book);
        Bundle extra = getIntent().getExtras();
        extra.putSerializable("book", book);
        extra.putBoolean("from_latest_update", true);
        IntentUtil.startActivity(getActivity(), ContentActivity.class, extra);
    }

    @OnClick(R.id.press_text)
    public void onPressClick(View v) {
        Bundle data = new Bundle();
        data.putString("press", book.getPress());
        IntentHelper.startActivity(this, PressBookListActivity.class, data);
    }

    @OnClick(R.id.author_layout)
    public void onAuthorClick(View v) {
        Bundle data = new Bundle();
        data.putString("author", book.getAuthor());
        IntentHelper.startActivity(this, AuthorBookListActivity.class, data);
    }

    @OnClick(R.id.back)
    public void onBackClick(View v) {
        finish();
    }

    @OnClick(R.id.intro_abbr_indicator)
    public void onAbbrIndicatorClick(View v) {
        if (showAbbrIntroduce) {
            introduce.setMaxLines(Integer.MAX_VALUE);
            showAbbrIntroduce = false;
            introduceAbbrIndicator.setImageResource(R.drawable.icon_arrow_up);
        } else {
            introduce.setMaxLines(3);
            showAbbrIntroduce = true;
            introduceAbbrIndicator.setImageResource(R.drawable.icon_arrow_down);
        }
        introduce.invalidate();
    }

}
